package com.jie.aspect;

import com.jie.annotation.DemoEventListenerResult;
import com.jie.entity.Article;
import com.jie.enums.ArticleFlowEvent;
import com.jie.enums.ArticleFlowStateEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.messaging.Message;
import org.springframework.statemachine.StateMachine;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @Author: 杰
 * @Project :net-disk
 * @DateTime: 2024/5/30 15:26
 **/
@Aspect
@Slf4j
@Component
public class DemoEventListenerResultAspect {
    @Resource
    private StateMachine<ArticleFlowStateEnum, ArticleFlowEvent> stateMachine;
    @Pointcut("@annotation(com.jie.annotation.DemoEventListenerResult)")
    public void logResult() {

    }
    @Around("logResult()")
    public Object logResultAround(ProceedingJoinPoint pjp) throws Throwable{
        //获取参数
        Object[] args=pjp.getArgs();
        log.info("参数args{}",args);
        Message message =(Message) args[0];
        Article article = (Article)message.getHeaders().get("article");
        //获取方法
       Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        //获取注解
        DemoEventListenerResult demoEventListenerResult = method.getAnnotation(DemoEventListenerResult.class);
        String key = demoEventListenerResult.key();
        Object returnVal=null;
        try{
            log.info("执行代理方法");
            returnVal=pjp.proceed();
            //如果成功为1 保存信息
            log.info("代理方法执行完成，保存状态信息");
            stateMachine.getExtendedState().getVariables().put(key+article.getId(),1);
        } catch (Throwable e) {
            stateMachine.getExtendedState().getVariables().put(key+article.getId(),0);
            log.error("失败");
        }
        return returnVal;
    }

}
